package bbs2.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bbs2.dao.DB;

import java.io.*;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet("/FileDownloadServlet")
public class FileDownloadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        InputStream input = null;
        BufferedOutputStream output = null;
        try {
            int ID = Integer.parseInt(request.getParameter("id"));
            conn = DB.getConnection();        
            String sql = "SELECT [fileName], [Data] FROM [File] WHERE [ID] = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, ID);
            rs = stmt.executeQuery();
            if (rs.next()) {
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment;filename=" + rs.getString("fileName") + ";");
                Blob blob = rs.getBlob("Data");
                input = blob.getBinaryStream();
                output = new BufferedOutputStream(response.getOutputStream());
                int count = 0;
                byte buffer[] = new byte[2048];
                while ((count = input.read(buffer)) != -1)
                    output.write(buffer, 0, count);
            }
        } catch (Exception e) {
            throw new ServletException(e);
        } finally {
            try {
                if (output != null) output.close();
                if (input != null) input.close();
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (Exception e) {}
        }
    }

}
